function paginationCountInfo(){
	var visitGuid=$("#visitGuid").val();
	var basePath = $("#basePath").val();
	$.ajax({
		type:"get",
		data:{visitGuid:visitGuid},
		url: basePath+"medical_record_pagination/pagination_count_info",
		success:function(data){
			var success = data['success'];
			if(success){
				var paginationCountInfo = data['data'];
				$("#totalFileCount").html(paginationCountInfo.totalPaginationCount);
				$("#unPaginationSpan").html(paginationCountInfo.unPaginationCount);
			}
		}
	})
}



function checkNumber(theObj) {
  var reg = /^[0-9]+.?[0-9]*$/;
  if (reg.test(theObj)) {
    return true;
  }
  return false;
}


function sort_li(a, b){
	var imageSortIndexB =$(b).attr('image-sort-index');
	var imageSortIndexA =$(a).attr('image-sort-index');
	var pageTypeSortIndexB=$(b).attr('page-type-sort-index');
	var pageTypeSortIndexA=$(a).attr('page-type-sort-index');

	if((pageTypeSortIndexB == pageTypeSortIndexA)){
		if(checkNumber(imageSortIndexB) && checkNumber(imageSortIndexA)){
			 return Number(imageSortIndexB) < Number(imageSortIndexA) ? 1 : -1;
		}
	}
    return Number($(b).attr('page-type-sort-index')) < Number($(a).attr('page-type-sort-index')) ? 1 : -1;    //升序排列
}

function existsSBatchChoose() {
	var flag = false;
	$("#filepage li").each(function(index) {
		if ($(this).attr("s_batchChoose")=='s_batchChoose') {
			flag = true;
		}
	});

	return flag;
}

function getBatchChooseIndex(str) {
	var batchChooseindex = -1;

	$("#filepage li").each(function(index) {
		if($(this).attr(str) ) {
			batchChooseindex = index;
		}
	});
	return batchChooseindex;
}

function chooseLabelModal(startIndex, endIndex) {
	var startIndex1 = Math.min(startIndex, endIndex);
	var endIndex1 = Math.max(startIndex, endIndex);
	console.log(startIndex+"--"+endIndex);
	$("#batchChooseTemplate_startIndex").val("");
	$("#batchChooseTemplate_endIndex").val("");
	$("#batchChooseTemplate_startIndex").val(startIndex);
	$("#batchChooseTemplate_endIndex").val(endIndex);
	$('#batchChooseTemplate').modal('show');
}

function submitBatchPaginantion(mrPageTypeCode,mrPageTypeName) {
	var startIndex = $("#batchChooseTemplate_startIndex").val();
	var endIndex = $("#batchChooseTemplate_endIndex").val();
	console.log("mrPageTypeCode="+mrPageTypeCode);
	batchPaginaionAjax(startIndex, endIndex, mrPageTypeCode,mrPageTypeName);

}

function getScanImageIds(startIndex, endIndex) {
	var scanImageIds ="";
	$("#filepage li").each(function(index) {
		if (index >= startIndex && index <= endIndex) {
			scanImageIds+="&scanImageIds="+$(this).attr("id");
		}
	});
    return scanImageIds;
}


function batchPaginaionAjax(startIndex, endIndex, mrPageTypeCode,mrPageTypeName) {
  	var visitGuid = $("#visitGuid").val();
  	var basePath = $("#basePath").val();
  	var scanImageIds  = getScanImageIds(startIndex, endIndex);
  	var postData = "mrPageTypeCode="+mrPageTypeCode;
  	postData+="&mrPageTypeName="+mrPageTypeName;
  	postData+=scanImageIds;
 	$.ajax({
		type:"post",
		url:basePath+"medical_record_pagination/batch_image_pagination",
		/*data:{'fileHashs':fileHashs, 'mrPageTypeCode':mrPageTypeCode, 'visitGuid':visitGuid},*/
		data:postData,
		success:function(data){
			console.log(data);
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("1" == stateCode){
					window.location.reload();
				}else{
					layer.msg("批量编页失败错误！");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			 alert(XMLHttpRequest.status);
			 alert(XMLHttpRequest.readyState);
			 alert(textStatus);
		}
	});

}

function initPage(){
	$(document).keypress(function(event) {
		var focusType = $(':focus').first().attr("type");
		if(focusType){
			return;
		}

		var currentImage = $("#filepage li[checked='checked']").first();
		if(currentImage && currentImage.length > 0){
			var keyCode =String.fromCharCode(event.keyCode).toUpperCase();
			if (keyCode === "A") {
				//清除原来被选中的
				console.log("----按下了 A键----");
				if(currentImage.attr("s_batchChoose")=='s_batchChoose') {
					currentImage.removeAttr("s_batchChoose");
					currentImage.find('img').removeClass('TM');
				} else {
					currentImage.attr("s_batchChoose", "s_batchChoose");
					currentImage.siblings().removeAttr("s_batchChoose");
					currentImage.find('img').addClass('TM');
					currentImage.siblings().find('img').removeClass('TM');
				}
				//layer.msg('按A键成功!', {time:500});
			} else if (keyCode === "B") {
				console.log("-------按下了  B键--------");
				//判断之前是否选中了开始页,并且按下了 B键
				if (existsSBatchChoose()) {
					currentImage.attr("e_batchChoose", "e_batchChoose");
					currentImage.siblings().removeAttr("e_batchChoose");
					var sBatchChooseindex = getBatchChooseIndex("s_batchChoose");

					 if(sBatchChooseindex != -1) {
						 var eBatchChooseindex = getBatchChooseIndex("e_batchChoose");
						 //弹框选择编页的标签
						 chooseLabelModal(sBatchChooseindex, eBatchChooseindex);

					 }	else {
						 console.log('----选中了开始页,并且按下了 B键获取开始页的下标没有获取到!------');
					 }
				}  else {
					layer.msg("在按B之前,请先按A键!",{time:500});
				}
			} else {

				var mrPageTypeObjs = $("#pageTypeList li[data-key-code='"+keyCode+"']");
				if(mrPageTypeObjs.length == 1){
					var mrPageTypeObj = mrPageTypeObjs.first();
			      	var visitGuid = $("#visitGuid").val();
			     	var newPageTypeCode =  mrPageTypeObj.attr("page-type-code");
			     	var newPageTypeName =  mrPageTypeObj.attr("title");
			     	var pageTypeSortIndex =mrPageTypeObj.attr("page-type-sort-index");
			     	var filehash = currentImage.attr("file-hash");
			     	var oldPageTypeCode = currentImage.attr("page-type-code");
			     	var scanImageId = currentImage.attr("id");
			     	paginationImage(currentImage,visitGuid,scanImageId,newPageTypeCode,newPageTypeName,oldPageTypeCode,pageTypeSortIndex);
				}
			}
		}

	});

paginationCountInfo();
var basePath = $("#basePath").val();
$(".file_header").on("click",function(){
  	$("#image_url li").css("border-color","#ccc").removeAttr("checked");//当前活动图片加红色边框,其他兄弟边框还是默认灰色
    $("#image_url li[page-type-code]").css("border-color","green");
  })
//获取图片列表
var filepage=$("#filepage li[id!='template_li']");
filepage.sort(sort_li)
        .appendTo('#filepage ul');

//获取编目菜单列表
var menulist=$("#pageTypeList li");
/*//获取未编页图片列表
var unPaginationFile=$("#filepage li[data-filename='0']");
$("#unPaginationSpan").html(unPaginationFile.length);*/
//定义未点击的图片
//var filename,menuname;

//点击图片列表
$.each(filepage,function(i,item){

    $(item).on("click",function(){
       $(this).css("border-color","red").siblings().css("border-color","#ccc");//当前活动图片加红色边框,其他兄弟边框还是默认灰色
       $(this).siblings("[page-type-code]").css("border-color","green");
       var checkedImages = $("#filepage li[checked='checked']");
       $("#filepage li").removeAttr("checked");
       $(this).attr("checked","checked");
       $("#pageTypeList li").css("background","#F7F8F8");
       var mr_page_type_code =$(this).attr("page-type-code");
       $("#pageTypeList li[id='"+mr_page_type_code+"']").css("background","#a6c9e2");
    });

})


//点击菜单绑定列表
$.each(menulist,function(i,item){
	var pageTypeCode = $(item).attr('page-type-code');
	var basePath = $("#basePath").val();
    $(item).on("click",function(){
      $(this).css("background","#a6c9e2").siblings().css("background","#F7F8F8");//当前活动菜单加橘黄色背景，其他的还是默认灰色背景

      var checkedImage = $("#filepage li[checked='checked']");
      if(checkedImage.length != 0){
      	var currentImage = checkedImage.get(0);
      	var visitGuid = $("#visitGuid").val();
     	var newPageTypeCode =  $(this).attr("page-type-code");
     	var newPageTypeName =  $(this).attr("title");
     	var pageTypeSortIndex =$(this).attr("page-type-sort-index");
     	var filehash = currentImage.getAttribute("file-hash");
     	var oldPageTypeCode = currentImage.getAttribute("page-type-code");
     	var scanImageId = currentImage.getAttribute("id");
     	$.ajax({
			type:"post",
			url: basePath+"medical_record_pagination/image_pagination",
			data:{visitGuid:visitGuid,scanImageId:scanImageId, newPageTypeCode:newPageTypeCode,newPageTypeName:newPageTypeName,oldPageTypeCode:oldPageTypeCode},
			success:function(data){
				console.log(data);
				var success = data['success'];
				if(success){
					var stateCode = data['stateCode'];
					if("1" == stateCode){
						$("#image_url li[id='"+scanImageId+"']").attr("page-type-code",newPageTypeCode).attr("page-type-sort-index",pageTypeSortIndex);
						var newPaginationCountInfo = data['data'];
						if(newPageTypeCode != null){
							var paginationCount = newPaginationCountInfo[newPageTypeCode];
							$("#pageTypeList span[id='page-type-code"+newPageTypeCode+"']").html(paginationCount);
						}
						if(oldPageTypeCode != null){
							var paginationCount = newPaginationCountInfo[oldPageTypeCode];
							$("#pageTypeList span[id='page-type-code"+oldPageTypeCode+"']").html(paginationCount);
						}
						var pagination = $("#pagination").val();
						var nextImage = $(currentImage).next();
						if(pagination ==1){
							$("#image_url li").css("border-color","#ccc").removeAttr("checked");//当前活动图片加红色边框,其他兄弟边框还是默认灰色
							checkedImage.remove();

						}else{
							var filepages=$("#filepage li[id!='template_li']");
				        	filepages.sort(sort_li).appendTo('#filepage ul');
						}
						$("#image_url li").removeAttr("checked");
    					$("#image_url li[page-type-code]").css("border-color","green");
    					if(nextImage.length > 0){
    						var paginationStatus = $("#pagination").val();
    						if(paginationStatus == 1){
    							nextImage.click();
    						}
    					}

						paginationCountInfo();
					}else{
						layer.msg("未预期错误！");
					}
				}else{
					layer.msg("病案编页失败！");
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(errorThrown);
				layer.msg("病案编页失败！");
			}
		});

      }
      else{
      	 var menuname=$(this).attr("page-type-code");
      	 var current_index = 0;
      	 var newFilepage=$("#filepage li[id!='template_li']");
		 $.each(newFilepage,function(i,item){
            /*判断li中data-filename是否跟menuname一样*/
            if($(item).attr("page-type-code")==menuname){
            	if(current_index == 0){
            		/*获取该标签距离顶部的高度*/
                    var $objTop=$(item)[0].offsetTop;
                    /*获取文件图片第一个li的offsetTop*/
                    var $firstTop=$(newFilepage).get(0).offsetTop;
                    /*当前li要滚动的总高度*/
                    var h=$objTop-$firstTop;
                    $(".filePage").animate({
                     scrollTop: h
                     },500);
                     current_index = 1;
            	}
            }
        })
      }
    });
});
}

function paginationImage(checkedImage,visitGuid,scanImageId,newPageTypeCode,newPageTypeName,oldPageTypeCode,pageTypeSortIndex){
	var basePath = $("#basePath").val();
	$.ajax({
		type:"post",
		url: basePath+"medical_record_pagination/image_pagination",
		data:{visitGuid:visitGuid,scanImageId:scanImageId, newPageTypeCode:newPageTypeCode,newPageTypeName:newPageTypeName,oldPageTypeCode:oldPageTypeCode},
		success:function(data){
			console.log(data);
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("1" == stateCode){
					$("#image_url li[id='"+scanImageId+"']").attr("page-type-code",newPageTypeCode).attr("page-type-sort-index",pageTypeSortIndex);
					var newPaginationCountInfo = data['data'];
					if(newPageTypeCode != null){
						var paginationCount = newPaginationCountInfo[newPageTypeCode];
						$("#pageTypeList span[id='page-type-code"+newPageTypeCode+"']").html(paginationCount);
					}
					if(oldPageTypeCode != null){
						var paginationCount = newPaginationCountInfo[oldPageTypeCode];
						$("#pageTypeList span[id='page-type-code"+oldPageTypeCode+"']").html(paginationCount);
					}
					var pagination = $("#pagination").val();
					var nextImage = checkedImage.next();
					if(pagination ==1){
						$("#image_url li").css("border-color","#ccc").removeAttr("checked");//当前活动图片加红色边框,其他兄弟边框还是默认灰色
						checkedImage.remove();

					}else{
						var filepages=$("#filepage li[id!='template_li']");
			        	filepages.sort(sort_li).appendTo('#filepage ul');
					}
					$("#image_url li").removeAttr("checked");
					$("#image_url li[page-type-code]").css("border-color","green");
					if(nextImage.length > 0){
						var paginationStatus = $("#pagination").val();
						if(paginationStatus == 1){
							nextImage.click();
						}

					}
					paginationCountInfo();
				}else{
					layer.msg("未预期错误！");
				}
			}else{
				layer.msg("病案编页失败！");
			}

		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(errorThrown);
			layer.msg("病案编页失败！");
		}
	});
}

function sortImage(obj){
	var basePath = $("#basePath").val();
	layer.confirm("您确认要修改图片顺序吗?请确认!", {
        btn : [ '确认', '取消' ]//按钮
    }, function(index) {
    	var $this = $(obj);
    	var $li = $this.closest("li");
    	var scanImageId = $li.attr("id");
    	var $input = $this.prev();
    	var sortIndex = $input.val();
    	layer.close(index);
    	if(sortIndex==null || sortIndex=="" || sortIndex==undefined){
    		 layer.alert('序列不能为空!',{icon:1});
    		return;
    	}

    	var reg = /^[0-9]+?[0-9]*$/;
		if (!reg.test(sortIndex)) {
			layer.alert('序列必须为数字!',{icon:1});
			return;
		}
    	$.ajax({
    		type:"post",
    		data:{scanImageId:scanImageId,sortIndex:sortIndex},
    		url: basePath+"medical_record_pagination/update_pagination_image_sort_index",
    		success:function(data){
    			console.log(data);
				var success = data['success'];
				if(success){
					var stateCode = data['stateCode'];
					if("1" == stateCode){
						$li.attr("image-sort-index",sortIndex);
			        	var filepages=$("#filepage li[id!='template_li']");
			        	filepages.sort(sort_li).appendTo('#filepage ul');
					}else{
						layer.msg("未预期错误！");
					}
				}
    		},
    		error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(errorThrown);
				layer.msg("修改图片顺序失败！");
			}
    	});
    });

}


function deleteImg(obj){
	var basePath = $("#basePath").val();
	if(!confirm("确定要删除吗？"))
	{
		return false;
	}
	var $this = $(obj);
   	var $li = $this.closest("li");
 		var scanImageId = $li.attr("id");
   	var visitGuid = $("#visitGuid").val();
   	var pageTypeCode =   $li.attr("page-type-code");
   	//alert(fileHash+"--"+firstGuid);
   	$.ajax({
		type:"post",
		url: basePath+"medical_record_pagination/remove_pagination_image",
		data:{visitGuid:visitGuid,scanImageId:scanImageId,currentPageTypeCode:pageTypeCode},
		success:function(data){
			console.log(data);
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("1" == stateCode){
					var newPaginationCountInfo = data['data'];
					if(pageTypeCode != null){
						var paginationCount = newPaginationCountInfo[pageTypeCode];
						$("#pageTypeList span[id='page-type-code"+pageTypeCode+"']").html(paginationCount);
					}
					$li.remove();
					paginationCountInfo();
				}else{
					layer.msg("未预期错误！");
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(errorThrown);
			layer.msg("删除图片失败！");
		}
	});
}


function paginationShow(){
	var basePath = $("#basePath").val();
	var pagination = $("#pagination").val();
	var url = basePath+"medical_record_pagination/finish_pagination_images_info";
	var visitGuid = $("#visitGuid").val();
	if(pagination =="1"){
		var url = basePath+"medical_record_pagination/un_pagination_images_info";
	}
	$.ajax({
   		type:"get",
   		data:{visitGuid:visitGuid},
   		url:url,
   		success:function(data){
   			console.log(data);
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("1" == stateCode){
					$("#template_li").siblings("li").remove();
					var scanFiles = data['data'];
					for(var index in scanFiles){
					var scanFile = scanFiles[index];
						var add_content=$("#template_li").clone();
						add_content.removeAttr("hidden");
						add_content.attr("id",scanFile.image_id).attr("image-sort-index",scanFile.sort_index);
						add_content.attr("file-hash", scanFile.file_hash).attr("page-type-sort-index",scanFile.page_type_sort_index);
						add_content.find("img").attr("src",basePath+"medical_record_scan/ajax_image_stream?fileHash="+scanFile.file_hash);
						add_content.find("input").val(scanFile.sort_index);
						var mr_page_type_code = scanFile.mr_page_type_code;
						if(mr_page_type_code){
							add_content.attr("page-type-code",mr_page_type_code).css("border-color","green");
						}
						add_content.on("click",function(){

				            $(this).css("border-color","red").siblings().css("border-color","#ccc");//当前活动图片加红色边框,其他兄弟边框还是默认灰色
				           	$(this).siblings("[page-type-code]").css("border-color","green");
				           	var checkedImages = $("#filepage li[checked='checked']");

				           	$(this).attr("checked","checked");
				           	$("#pageTypeList li").css("background","#F7F8F8");
				            var mr_page_type_code =$(this).attr("page-type-code");
       						$("#pageTypeList li[id='"+mr_page_type_code+"']").css("background","#a6c9e2");
				        }).keypress(function(event) {
				        	var checkedStr = $(this).attr("checked");
				        	var focusType = $(':focus').first().attr("type");
				    		if (checkedStr == "checked") {
				    			if(!focusType){
				    				var keyCode =String.fromCharCode(event.keyCode).toUpperCase();
				    				var mrPageTypeObjs = $("#pageTypeList li[data-key-code='"+keyCode+"']");
				    				if(mrPageTypeObjs.length == 1){
				    					var mrPageTypeObj = mrPageTypeObjs.first();
				    					var currentImage = $(this);
				    			      	var visitGuid = $("#visitGuid").val();
				    			     	var newPageTypeCode =  mrPageTypeObj.attr("page-type-code");
				    			     	var newPageTypeName =  mrPageTypeObj.attr("title");
				    			     	var pageTypeSortIndex =mrPageTypeObj.attr("page-type-sort-index");
				    			     	var filehash = currentImage.attr("file-hash");
				    			     	var oldPageTypeCode = currentImage.attr("page-type-code");
				    			     	var scanImageId = currentImage.attr("id");
				    			     	paginationImage(currentImage,visitGuid,scanImageId,newPageTypeCode,newPageTypeName,oldPageTypeCode,pageTypeSortIndex);
				    				}

				    			}

				    		}

				    	})
						$("#image_url").append(add_content);
					}
		        	var filepages=$("#filepage li[id!='template_li']");
		        	filepages.sort(sort_li).appendTo('#filepage ul');
				}else{
					layer.msg("未预期错误！");
				}
			}
   		},
   		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(errorThrown);
			layer.msg("操作失败！");
		},
		complete:function(XMLHttpRequest, textStatus){

		}
   	});

	var add_content=$("#template_li").clone();
	add_content.removeAttr("hidden");

}

function imagePaginationFinish(){
	var basePath = $("#basePath").val();
	var visitGuid = $("#visitGuid").val();
	layer.load(1);
	$.ajax({
		url: basePath + "medical_record_scan/ajax_image_pagination_finish",
		dataType: "json",
		type: "POST",
		data:{visitGuid:visitGuid},
		success: function( data ) {
			var success = data['success'];
			if(success){
				var resultShow = data['data'];
				layer.msg(resultShow);
			}else{
				layer.msg("操作错误，请重试！");
			}
			console.log(data);

		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			layer.msg("网络或未知错误，请联系管理员");
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
		}
	});

};
